#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->ipLineEdit->setText("192.168.4.1");//设置初值
    ui->portLineEdit->setText("8080");//设置初值
    socket = new QTcpSocket;//创建一个socket对象
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_cancleButton_clicked()
{
    this->close();
}

void Widget::on_connectButton_clicked()
{
    //获取ip地址和端口号
    QString IP = ui->ipLineEdit->text();
    QString Port = ui->portLineEdit->text();

    //连接服务器
    socket->connectToHost(QHostAddress(IP),Port.toShort());

    //连接服务器成功，socket对象会发出信号
    connect(socket,&QTcpSocket::connected,[this]()
    {
        QMessageBox::information(this,"连接提示","连接服务器成功");//提示框

        this->hide();//隐藏当前界面
        Chat *c = new Chat(socket);//堆空间创建对象不会被释放
        c->show();
    });

    //连接断开，socket也会发出信号
    connect(socket,&QTcpSocket::disconnected,[this]()
    {
        QMessageBox::information(this,"连接提示","连接异常，网络断开");//提示框
    });
}
